package com.hbnu.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author kittychen
 * @since 2025-10-30 20:07
 */
public class TcpClientDemo02 {
    public static void main(String[] args) {
        Socket socket = null;
        try {
            // 1、创建socket
            socket = new Socket("127.0.0.1", 8888);

            // 2、获取流资源
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();

            // 3、发送数据
            outputStream.write("土豆土豆，我是地瓜，收到请回复，over".getBytes());

            // 4、接收数据
            byte[] buffer = new byte[1024];
            int len = inputStream.read(buffer);
            System.out.println("服务端返回的数据：" + new String(buffer, 0, len));
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 5、释放资源
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
